<?php
namespace Admin\Controller;

/**
 * 前台首页控制器
 */
class OrderController extends AdminController {
    
    // show all the orders
    public function index(){
        /* 查询条件初始化 */
        $map = array();
        $map  = array('delflag' => 0);
        $status = I('status', false);
        $oid = I('oid', false);
        if($status){
            $map['isWithdrawal'] = intval($status);
        }
        if($oid){
            $map['oid'] = array('like', '%'.$oid);
        }
        $list   = $this->lists('Order', $map);
        int_to_string($list);
        $this->assign('list', $list);
        $this->meta_title = '订单列表';
        $this->display();
    }

    // save the orders to db
    public function save(){
        $datas = S('ORDERS');
        $m = M('Order');
        if($m->addAll($datas)){
            // 删除缓存
            S('ORDERS', null);
            $this->success('订单写入成功');
        }else{
            $this->error('订单写入失败');
        }
    }

    // upload and parse the orders.xls from pub.alimama.com
    public function upload(){
        if(IS_POST){
            if ($_FILES["file"]["error"] > 0){
                $this->error($_FILES["file"]["error"]);
            }else{
                $file_name = $_FILES["file"]["tmp_name"];
                vendor("PHPExcel.PHPExcel");
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objPHPExcel = $objReader->load($file_name, $encode='utf-8');
                $sheet = $objPHPExcel->getActiveSheet();
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                $highestColumn = $sheet->getHighestColumn(); // 取得总列数
                $list = array();
                $info = array('payed' => 0, 'cancel' => 0, 'total' => $highestRow - 1, 'deal' => 0);
                // start from row 2
                for($i = 2, $counter = 0; $i <= $highestRow; $i++){
                    $data = array();
                    $data['oid']=  $sheet->getCell("Y".$i)->getValue();
                    $data['createTime']=  $sheet->getCell("A".$i)->getValue();
                    $data['status']=  $sheet->getCell("I".$i)->getValue();
                    if($data['status'] === '订单付款'){
                        $info['payed'] = $info['payed'] + 1;
                    }elseif($data['status'] === '订单失效'){
                        $info['cancel'] = $info['cancel'] + 1;
                    }elseif($data['status'] === '订单结算'){
                        $info['deal'] = $info['deal'] + 1;
                        $data['amount']=  $sheet->getCell("M".$i)->getValue();
                        $data['dealTime']=  $sheet->getCell("Q".$i)->getValue();
                        $data['commissionAmount']=  $sheet->getCell("S".$i)->getValue();
                        $data['subsidyAmount']=  $sheet->getCell("U".$i)->getValue();
                        $data['productId'] = $sheet->getCell("D".$i)->getValue();
                        $data['productName'] = $sheet->getCell("C".$i)->getValue();
                        $data['productCount'] = $sheet->getCell("G".$i)->getValue();
                        $data['productPrice'] = $sheet->getCell("H".$i)->getValue();
                        $data['shopName'] = $sheet->getCell("F".$i)->getValue();
                        $data['rowId']= ++$counter;
                        array_push($list, $data);
                    }
                }
                S('ORDERS', $list, array('type'=>'file','expire'=>30000));
                $this->assign('info', $info);
                $this->assign('list', $list);
                $this->display();
            }
            
        }else{
            $this->display();
        }
    }

    public function apply_approve(){
        $id = $_REQUEST['id'];
        $oids = I('ids');
        $m = M('Order');
        $orders = $m->where(array('id' => array('in', $oids), 'isWithdrawal' => 0))->select();
        if(!$orders){
            $this->error('未匹配任何订单信息');
            return;
        }
        $total_amount = 0;
        $products = '';
        // sum the products
        // sum the amount
        foreach($orders as $o){
            $total_amount = $total_amount + floatval($o['commissionAmount']);
            $products = $products. $o['productName']. ' + ';
        }
        
        $fanli_off = C('FANLI_USER_OFF');
        if(!$fanli_off){
            $fanli_off = 0.5;
        }
        $total_amount  = round($total_amount * $fanli_off, 2); //取小数点后2位
        

        // update fanli apply
        $m = M('FanliApply');
        $clientid = $m->where(array('id' => intval($id)))->getField('client');
        

        $now = time();
        $r1 = $m->where(array('id' => intval($id)))->save(array(
            'status' => 'DEAL',
            'dealAt' => $now,
            'updateAt' => $now,
            'products' => $products,
            'commissionAmount' => $total_amount,
        ));
        if($r1){
            // update orders
            $m = M('Order');
            $r2 = $m->where(array('id' => array('in', $oids), 'isWithdrawal' => 0))->save(array(
                'isWithdrawal' => 1,
                'withdrawalAt' => $now,
                'fanli_id' => intval($id),
            ));
            if($r2){
                //update client balance
                $m = M('Client');
                $amount_number = intval($total_amount * 100);
                $r3 = $m->where(array('id' => intval($clientid)))->setInc('balance' , $amount_number);
                if($r3){
                    // update the parentDistributor 
                    $parentid = $m->where(array('id' => intval($clientid)))->getField('parentDistributor');
                    //if parentDis not equal -1
                    if(intval($parentid) != -1){
                        // default give the 30% of the fanli amount 
                        $r4 = $m->where(array('id' => intval($parentid), 'delflag' => 0, 'isDistributor' => 1))->setInc('balance' , $amount_number * 0.6);
                        if($r4 === false){
                            // equal false ,means 注意：save方法的返回值是影响的记录数，如果返回false则表示更新出错，因此一定要用恒等来判断是否更新失败。
                            $this->error('受理失败4');
                            return;
                        }
                    }
                    $this->success('受理成功');
                }else{
                    $this->error('受理失败3');
                }
            }else{
                
            }
        }else{
            $this->error('受理失败2');
        }

        
    }

    public function apply_reject(){
        $id = I('id');
        $m = M('FanliApply');
        $now = time();
        $r = $m->where(array('id' => intval($id)))->save(array(
            'status' => 'REJECT',
            'dealAt' => $now,
            'updateAt' => $now,
        ));
        if($r){
            $this->success('处理完成');
        }else{
            $this->error('处理失败');
        }
    }

    public function apply_handle(){
        $id = I('id');
        // fetch data
        $m = M('FanliApply');
        $data = $m->where(array('id' => $id))->find();
        if($data){
            $oid = $data['orders'];
            $m = M('Order');
            $orders = $m->where(array('oid' => array('like', '%'.$oid)))->select();
            $this->assign('orders', $orders);
        }else{
            $this->error('该信息不存在');
            return;
        }
        $this->assign('apply', $data);
        $this->display();
    }

    public function apply(){
        /* 查询条件初始化 */
        $map = array();
        $map  = array('delflag' => 0);
        $status = I('status');
        $oid = I('oid');
        if($status){
            $map['status'] = $status;
        }
        if($oid){
            $map['oid'] = array('like', '%'.$oid);
        }
        $list   = $this->lists('FanliApply', $map);
        int_to_string($list);
        $this->assign('list', $list);
        $this->assign('status', $status);
        $this->assign('oid', $oid);
        $this->meta_title = '订单列表';
        $this->display();
    }




}
?>